#include "iblog_in.h"

int OnAppProcess( struct IblogEnv *p_env , struct AcceptedSession *p_accepted_session )
{
	struct IblogHandle	log_handle ;
	struct IblogHandle	*p_log_handle = NULL ;
	
	int			nret = 0 ;
	
	if( p_accepted_session->comm_buf[4] == '0' )
	{
		memset( & log_handle , 0x00 , sizeof(struct IblogHandle) );
		strncpy( log_handle.log_pathfilename , p_accepted_session->comm_buf+5 , MIN(sizeof(log_handle.log_pathfilename)-1,p_accepted_session->comm_body_len-1) );
		p_log_handle = QueryIblogHandleTreeNode( p_env , & log_handle ) ;
		if( p_log_handle )
		{
			p_accepted_session->p_log_handle = p_log_handle ;
		}
		else
		{
			p_log_handle = (struct IblogHandle *)malloc( sizeof(struct IblogHandle) ) ;
			if( p_log_handle == NULL )
			{
				ERRORLOGG( "malloc failed , errno[%d]" , errno );
				return HTTP_INTERNAL_SERVER_ERROR;
			}
			memset( p_log_handle , 0x00 , sizeof(struct IblogHandle) );
			
			p_log_handle->g = CreateLogHandle() ;
			nret = SetLogOutput2( p_log_handle->g , LOG_OUTPUT_FILE , LOG_NO_OUTPUTFUNC , "%s/%s" , getenv("HOME") , p_accepted_session->comm_buf+5 ) ;
			if( nret )
			{
				ERRORLOGG( "SetLogOutput failed[%d]" , nret );
				free( p_log_handle );
				return HTTP_INTERNAL_SERVER_ERROR;
			}
			SetLogLevel( p_log_handle->g , LOG_LEVEL_DEBUG );
			SetLogStyles( p_log_handle->g , LOG_STYLE_FORMAT , LOG_NO_STYLEFUNC );
			
			p_log_handle->ref_count++;
			
			strncpy( p_log_handle->log_pathfilename , p_accepted_session->comm_buf+5 , MIN(sizeof(p_log_handle->log_pathfilename)-1,p_accepted_session->comm_body_len-1) );
			nret = LinkIblogHandleTreeNode( p_env , p_log_handle ) ;
			if( nret )
			{
				ERRORLOGG( "LinkIblogHandleTreeNode failed[%d]" , nret );
				DestroyLogHandle( p_log_handle->g );
				free( p_log_handle );
				return HTTP_INTERNAL_SERVER_ERROR;
			}
			
			p_accepted_session->p_log_handle = p_log_handle ;
		}
	}
	else if( p_accepted_session->comm_buf[4] == '1' )
	{
		if( p_accepted_session->p_log_handle == NULL || p_accepted_session->p_log_handle->g == NULL )
		{
			ERRORLOGG( "log file not opened" );
			return HTTP_BAD_REQUEST;
		}
		
		WRITELOG( p_accepted_session->p_log_handle->g , p_accepted_session->comm_buf[5]-'0' , "%s" , p_accepted_session->comm_buf+6 );
	}
	else
	{
		ERRORLOGG( "type[c] invalid" , p_accepted_session->comm_buf[4] );
		return HTTP_BAD_REQUEST;
	}
	
	return HTTP_OK;
}

